const koa       = require('koa'),
      parameter = require('koa-parameter');

const app = koa();

// add verifyParams method, but don't add middleware to catch the error
// app.use(parameter(app)); // also add a middleware to catch the error.
parameter(app);

function *errHandler(ctx, e) {
    ctx.body = {
        success: false,
        errors : e.errors
    };
}

app.use(function *(next) {
    try {
        yield next;
    } catch (e) {
        yield errHandler(this, e);
    }
});

// 访问 查看结果
/**
 * 访问以下链接查看结果对比
 *   http://localhost:3000/?id=1
 *   http://localhost:3000/?id=a
 *   http://localhost:3000/?date=2016-01-01
 *   http://localhost:3000/?date=2016
 *   http://localhost:3000/?id=1&date=2016-01-01
 */
app.use(function *() {
    // 更多的验证规则参考 https://github.com/node-modules/parameter#rule
    this.verifyParams({
        id  : 'id',
        date: 'date'
    });
    this.body = 'verify passed';
});

app.listen(3000);